var http = require('http');
const jwt = require('jsonwebtoken');
import configFile from './config';
import {base64} from './core/enco';
import app from './app';
import mongodbHandle from './handle/mongodbHandle'
import routeHandle from './handle/adminRouteHandle'
import redisHandle from './handle/redisHandle';
import * as url from 'url'
var log4js = require('log4js')

if (process.argv.length >= 2 && configFile[process.argv[2]]) {
    app.env = process.argv[2]
    app.config = configFile[app.env]
} else {
    app.env = 'adminDev'
    app.config = configFile['adminDev']
}
log4js.configure(app.config.log4js)

app.logger = log4js.getLogger('default')


function getResData(data) {
    data.time = new Date().getTime()
    data.version = app.version
    data = JSON.stringify(data)
    if (app.env == 'pro' || app.env == 'demo') {
        data = base64.encode(data)
    }
    return data
}

let init = async () => {
    await redisHandle.init(app.env)
    await mongodbHandle.init(app.env)
    // if (app.env == 'demo' || app.env == 'dev') {
    //     await mongodbHandle.initTest('mongodb://root:123456789qwe@183.56.208.170:27017', 'tower3pro')
    // }
    var httpapp = async (req, res) => {
        res.setHeader('Access-Control-Allow-Credentials', 'true');
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.setHeader("Access-Control-Allow-Headers", "X-Requested-With,cache-control,content-type,hash-referer,authorization");
        // //升级维护中
        // res.end(
        //     getResData({
        //         err: 110,
        //         data: ''
        //     })
        // )
        // return
        let reqs = req.url.split('/')
        let api = reqs[reqs.length - 2]
        let reqUrl = reqs[reqs.length - 1]
        if (req.method === 'GET' || req.method === 'get') {
            console.log(req.url)
            if (reqUrl.indexOf("notifycharge") !== -1) {
                let query = url.parse(req.url).query
                let data = {}
                query.split('&').forEach(item => {
                    let d = item.split('=')
                    data[d[0]] = d[1]
                })
                let resData = await routeHandle("notifycharge", data, null)
                res.end(getResData(resData))

            }
        } else if (req.method === 'POST' || req.method === 'post') {
            var data = "";
            req.on("data", (chunk) => {
                data += chunk;
            })
            req.on("end", async () => {
                let token = req.headers.authorization
                let dataJson
                if (api == 'api') {
                    try {
                        if (app.env == 'pro' || app.env == 'demo') {
                            data = base64.decode(data)
                        }
                        dataJson = JSON.parse(data);
                    } catch (e) {
                        res.end(
                            getResData({
                                err: 105,
                                data: e.message
                            })
                        )
                    }
                    if (token) {
                        jwt.verify(token, "secretkey", async (err, decode) => {
                            if (!err) {
                                let resData = await routeHandle(reqUrl, dataJson, decode)
                                res.end(getResData(resData))
                            } else {
                                let resData = await routeHandle(reqUrl, dataJson, null)
                                res.end(getResData(resData))
                            }
                        })
                    } else {
                        let resData = await routeHandle(reqUrl, dataJson, null)
                        res.end(getResData(resData))
                    }
                } else {
                    res.end()
                }
            })
        } else {
            res.end()
        }
    };

    var server = http.createServer(httpapp);

    //监听端口
    server.listen(app.config.port);
    console.log('服务器环境:' + (app.env));
    console.log('服务器端口:' + app.config.port);
}


init()